/*
* 新收费页面
* */

import React, { Component } from 'react';
import { Input, Form, Select, Modal, Button, Divider, Icon, message, Radio, Row, Col } from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const InputGroup = Input.Group;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

class NewShowRegistrModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      payWayId: '',
      payWayMoney: '0',
      realPayMoney: '',
      radioValue: '1',
      showType: true,
      otherPayMoney: 0,
      cashPayMoney: 0,
      realPayMoney:''
    }
    this.payWayFocus = React.createRef()
    this.realMoneyFocus = React.createRef()
    this.comFirmFocus = React.createRef()
  }

  componentWillReceiveProps(nextProp) {
    if (nextProp.isShow === true) {
      var newPayWay = this.props.newPayWay;
      if (!Util.isEmpty(this.props.newPayWay)) {
        this.setState({
          payWayId: this.props.newPayWay[0].paywID,
          selectCode: this.props.newPayWay[0].paywCode,
          otherPayWayId: this.props.newPayWay[1] ? this.props.newPayWay[1].paywID : '',
          // otherPayCode: this.props.newPayWay[1].paywCode,
        })
      }

    } else if (this.props.isShow === false) {
      this.cleanInput();
    }
  }

  //组件挂载完后，给对应的element焦点
  componentDidUpdate() {
    // this.realMoneyFocus.current && this.realMoneyFocus.current.focus()
  }

  closeModal() {
    //进行取消异常
    let { RollBACKOPCharge } = this.props;
    var rtn = RollBACKOPCharge();
    if (rtn) {
      this.cleanInput();
      let { onHide } = this.props;
      onHide && onHide();
    }
  }

  //清空输入框
  cleanInput() {
    this.props.form.resetFields();
    this.setState({
      hospitalId: '',
      realPayMoney: '',
      payWayMoney: 0,
      payWayId: undefined,
      cashPayMoney: 0,
      otherPayCode: '',
      otherPayMoney: 0,
      radioValue: '1',
      realPayMoney:''
    })
  }

  /**
   * @ByShizi: 挂号收费多种支付金额问题处理
   * Create 2022-03-23
  */
  onSubmit = async () => {
    var payWayCount = 0;//其他支付方式金额
    var realPayCount = 0;//现金支付金额
    let { updatePayModal } = this.props;
    var registrSumData = this.props.registrSumData;
    var maypayData = this.props.maypayData

    var { radioValue, realPayMoney, cashPayMoney, otherPayMoney, payWayId, otherPayWayId } = this.state;
    let checkAccount = false; // 是否院内账户

    //先计算金额
    var moneyData = this.props.moneyData
    var price = 0
    price = (moneyData ? moneyData.otherPayAmt ? moneyData.otherPayAmt : 0 : 0)
    cashPayMoney=(this.state.cashPayMoney) ? this.state.cashPayMoney:price
    if (radioValue == '1') { // 现金支付
      if (parseFloat(cashPayMoney) !== parseFloat(price)) {
        message.error('支付金额和应收金额不平，请重新核实！')
        return
      }
    } else {
      if (parseFloat(parseFloat(cashPayMoney)+parseFloat(otherPayMoney))!== parseFloat(price))
      {
        message.error('支付金额和应收金额不平，请重新核实！')
        return
      }
    }
    var paywIDinfo=payWayId + '^' + cashPayMoney + String.fromCharCode('2') + otherPayWayId + '^' + otherPayMoney
    //更新支付方式 并 结算确认
    updatePayModal(paywIDinfo)
  }

  commonInputChange(name, e) {
    var value = e.target.value;
    var reg = /(^[1-9][0-9]*$)|(^[1-9][0-9]*\.\d{0,2}$)|^0(?!\d)\.?\d{0,2}$|^[1-9]?$/;
    if (!reg.test(value)) {
      message.error('只允许输入正整数或者两位小数！')
      return
    }
    var otherPayMoney, cashPayMoney, realPayMoney;
    var moneyData = this.props.moneyData
    var hospMoney = 0
    hospMoney = (moneyData ? moneyData.otherPayAmt ? moneyData.otherPayAmt : 0 : 0)
    //先计算应收总金额
    if (name == 'cashPayMoney') {
      if (parseFloat(value) > hospMoney) {
        message.error('支付金额不能大于应收金额！')
        return
      }
      otherPayMoney = (hospMoney - parseFloat(value || 0)).toFixed(2)
      cashPayMoney = value
      this.setState({ cashPayMoney: cashPayMoney, otherPayMoney: otherPayMoney })

    } else if (name == 'otherPayMoney') {
      if (parseFloat(value) > hospMoney) {
        message.error('支付金额不能大于应收金额！')
        return
      }
      cashPayMoney = (hospMoney - parseFloat(value || 0)).toFixed(2)
      otherPayMoney = value
      this.setState({ otherPayMoney: otherPayMoney, cashPayMoney: cashPayMoney })

    } else if (name == 'realPayMoney') {
      let CASHamt=0
      if (this.state.selectCode == 'CASH')
      {
        CASHamt=parseFloat((this.state.cashPayMoney) ? this.state.cashPayMoney:hospMoney)+CASHamt
      }
      if (this.state.otherPayCode == 'CASH')
      {
        CASHamt=parseFloat(this.state.otherPayMoney || 0)+CASHamt
      }
      realPayMoney =parseFloat(value)-parseFloat(CASHamt)
      this.setState({ realPayMoney: realPayMoney })
    }
  }

  handleSelectChange(name, e, code) {
    this.setState({
      [name]: e,
      selectCode: code ? code.props.code : '',
      cashPayMoney: 0
    })
  }

  handleOtherSelectChange(name, e, code) {
    this.setState({
      [name]: e,
      otherPayCode: code ? code.props.code : '',
      otherPayMoney: 0
    })
  }

  changeRadio(e) {
    
    //先计算应收总金额
    var moneyData = this.props.moneyData
    var hospMoney = 0
    hospMoney = (moneyData ? moneyData.otherPayAmt ? moneyData.otherPayAmt : 0 : 0)
    if (e.target.value == '2') {
      this.setState({
        radioValue: e.target.value,
        cashPayMoney: 0,
        otherPayCode: this.props.newPayWay[1] ? this.props.newPayWay[1].paywCode : '',
      }, () => {
        this.payWayFocus.current.focus()
      })
    } else {
      this.setState({
        radioValue: e.target.value,
        cashPayMoney: hospMoney,
        otherPayCode: ''
      })
    }
  }

  changeShowType() {
    if (this.state.showType === true) {
      this.setState({
        showType: false
      })
    } else {
      this.setState({
        showType: true
      })
    }
  }

  keyDownComfirm(e) {
    if (e.keyCode == '13') {
      this.comFirmFocus.current.buttonNode.focus()
    }
  }

  onkeySubmit(e) {
    if (e.keyCode == '13') {
      this.onSubmit()
    }
  }

  onSubmitLeftElement(e) {
    this.onSubmit()
  }

  changeFocus(e) {
    if (e.keyCode == '13') {
      if (this.state.selectCode == 'CASH' || this.state.otherPayCode == 'CASH') {
        this.realMoneyFocus.current.focus()
      } else {
        this.comFirmFocus.current.buttonNode.focus()
      }
    }
  }

  render() {
    var payWayOption = []
    this.props.newPayWay && this.props.newPayWay.map((item, index) => {
      payWayOption.push(<Option key={index}
        disabled={(this.state.otherPayWayId == item.paywID && this.state.radioValue == '2') ? true : false} value={item.paywID} code={item.paywCode}>{item.paywDesc}</Option>)
    })
    var payWayOtherOption = []
    this.props.newPayWay && this.props.newPayWay.map((item, index) => {
      payWayOtherOption.push(<Option disabled={this.state.payWayId == item.paywID ? true : false} key={index} value={item.paywID} code={item.paywCode}>{item.paywDesc}</Option>)
    })
    var moneyData = this.props.moneyData
    var hospMoney = 0
    hospMoney = (moneyData ? moneyData.otherPayAmt ? moneyData.otherPayAmt : 0 : 0)
    return <div>
      <Modal className='new-registr-modal'
        title={'收费'}
        maskClosable={false}
        visible={this.props.isShow}
        onCancel={this.closeModal.bind(this)}
        // onOk={this.onSubmit.bind(this)}
        footer={<div><Button onClick={this.closeModal.bind(this)}>取消</Button>
          <Button className='time-save-button' ref={this.comFirmFocus}
            // onKeyDown={this.onkeySubmit.bind(this)}
            onClick={this.onSubmitLeftElement.bind(this)}>确定</Button></div>}>
        <div>
          <div>
            <Row>
              {this.props.maypayData && Array.isArray(this.props.maypayData) && this.props.maypayData.map((item, i) =>
                <Col span={12} key={i}>
                  <span style={{ marginLeft: 10, lineHeight: '35px', marginLeft: 27 }}>
                    <span>{item.desc}</span>
                    <span style={{ color: '#FA8C16' }}>{item.amt}</span>
                  </span>
                </Col>
              )}
            </Row>
            <div><Divider dashed={false}>应收</Divider></div>
            {/**应收金额 */}
            <div style={{ textAlign: 'center' }}>
              {/**实收金额-统筹金额-减免-院内金额 */}
              <div><span style={{ fontSize: '20px' }}>¥</span>
                <span style={{ color: '#FA541C', fontSize: '32px', marginLeft: 10 }}>{parseFloat(hospMoney)}</span></div>
            </div>

            {/**支付方式 */}
            <div style={{ height: 40 }}>
              <div>
                <span style={{ float: 'left', marginLeft: 27 }}>
                  支付方式<Select placeholder='请选择支付方式' style={{ width: 160, marginLeft: 5 }} getPopupContainer={triggerNode => triggerNode.parentNode}
                    value={this.state.payWayId} showSearch
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    onChange={this.handleSelectChange.bind(this, 'payWayId')}>
                    {payWayOption}</Select>
                </span>
                <span style={{ float: 'right', marginRight: 40, lineHeight: '35px' }}>
                  支付金额<Input style={{ width: 160, marginLeft: 5 }} addonBefore='¥' className='common-point-style'
                    ref={this.payWayFocus}
                    onKeyDown={this.changeFocus.bind(this)}
                    disabled={this.state.radioValue == '1' ? true : false}
                    value={(this.state.cashPayMoney) ? this.state.cashPayMoney : (this.state.radioValue == '2' ? '' : hospMoney)}
                    onChange={this.commonInputChange.bind(this, 'cashPayMoney')} />
                </span>
              </div>
            </div>
            <div>
              {this.state.radioValue == '2' ? <div style={{ marginTop: 10 }}>
                <span style={{ float: 'left' }}>
                  其他支付方式<Select placeholder='请选择支付方式' style={{ width: 160, marginLeft: 5 }} getPopupContainer={triggerNode => triggerNode.parentNode}
                    value={this.state.otherPayWayId}
                    onChange={this.handleOtherSelectChange.bind(this, 'otherPayWayId')}>
                    {payWayOtherOption}</Select>
                </span>
                <span style={{ float: 'right', marginRight: 40, lineHeight: '35px' }}>
                  支付金额<Input className='common-point-otherPayWay'
                    onChange={this.commonInputChange.bind(this, 'otherPayMoney')}
                    style={{ width: 160, marginLeft: 5 }} value={(this.state.otherPayMoney) ? this.state.otherPayMoney : 0}
                    addonBefore='¥' />
                </span>
              </div>
                : null}
            </div>

            {this.state.selectCode == 'CASH' || this.state.otherPayCode == 'CASH' ? <div><Divider dashed={false}>实收现金</Divider></div> : null}

            {this.state.selectCode == 'CASH' || this.state.otherPayCode == 'CASH' ? <div style={{ height: 40, lineHeight: '35px' }}>
              <span style={{ marginLeft: 27, float: 'left' }}>
                <span style={{ marginTop: 3 }}>实收现金</span><Input style={{ width: 160, marginLeft: 5 }}
                  ref={this.realMoneyFocus} autoFocus
                  onKeyDown={this.keyDownComfirm.bind(this)}
                  addonBefore='¥'
                  onChange={this.commonInputChange.bind(this, 'realPayMoney')} />
              </span>
              <span style={{ float: 'right', marginRight: 40 }}>
                找零<Input className='common-point-otherPayWay'
                  style={{ width: 160, marginLeft: 5 }} addonBefore='¥' disabled={true}
                  value={this.state.realPayMoney?this.state.realPayMoney: 0} />
              </span><br />
            </div> : null}

            {this.props.checked == true ? <div><Divider dashed={false}>病历本费</Divider></div> : null}

            {this.props.checked == true ? <div style={{ height: 40, lineHeight: '35px' }}>
              <span style={{ marginLeft: 27, float: 'left' }}>
                <span style={{ marginTop: 3 }}>病历本费</span><Input style={{ width: 160, marginLeft: 5 }} disabled
                  addonBefore='¥' value={this.props.medicalFee} />
              </span></div> : null}

            {/**切换支付方式 */}
            <div style={{ marginTop: 10, marginLeft: 27, display: 'inline-block' }}>
              <div>切换模式<RadioGroup style={{ marginLeft: 5 }} value={this.state.radioValue} onChange={this.changeRadio.bind(this)}>
                <Radio value='1'>单一支付</Radio>
                <Radio value='2'>组合支付</Radio>
              </RadioGroup></div>
            </div>
          </div>

          {/* {this.state.showType == true ? <div className='new-registr-right' style={{
            float: 'right', width: '20%',
            borderLeft: '1px solid #f1faf6', minHeight: '30vh', maxHeight: '50vh'
          }}>
            <div style={{ cursor: 'pointer' }} onClick={this.changeShowType.bind(this)}>
              <Icon type="double-left" />账单附录
            </div>
            <Divider />
            本年糖尿病累计（元）: 123.00
            </div> :
            <div className='hide-right-modal' onClick={this.changeShowType.bind(this)}>
              <Icon type='double-right' />账单附录
            </div>} */}
        </div>
      </Modal></div>
  }
}

export default Form.create()(NewShowRegistrModal);